import requests from '@/utils/request';
//封装好的api
export function downFile(url, parameter) {
  return requests({
    // url: '/admin/student/exportStudentData',
    url: url + parameter,
    method: 'post',
    // params: parameter,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    // headers: { 'Content-Type': 'application/x-download' },
    responseType: 'blob',
  });
}

/**
 * 下载文件
 * @param url 文件路径
 * @param fileName 文件名
 * @param parameter
 * @returns {*}
 */
export function downloadFile(url, fileName, parameter, type) {
  // console.log(url, fileName, parameter, type, '类型');
  let fileType = ''; //下载文件类型，项目需求要excel和word两种格式，有需要的伙伴可以自行搜索下其他格式进行替换即可
  switch (type) {
    case '.doc':
      fileType = 'application/msword';
      break;
    case '.xls':
      fileType = 'application/vnd.ms-excel';
      break;
  }
  return downFile(url, parameter).then((data) => {
    console.log(data);
    if (!data || data.size === 0) {
      Vue.prototype['$message'].warning('文件下载失败');
      return;
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName);
    } else {
      //核心
      let blob = new Blob([data], { type: fileType });
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放掉blob对象
    }
  });
}
